//
//  CZNetworkTool.swift
//  SinaSwift
//
//  Created by I Do Believe on 15/11/26.
//  Copyright © 2015年 apple11. All rights reserved.
//

import UIKit

import AFNetworking

 ///  网络单例
class CZNetworkTool: AFHTTPSessionManager {

    
    //单例
    static let sharedInstance : CZNetworkTool = {

        // baseURL
        let baseURL = NSURL(string: "https://api.weibo.com/")
        let tool = CZNetworkTool(baseURL: baseURL)
        
        //添加响应的序列化器
        tool.responseSerializer.acceptableContentTypes?.insert("text/plain")
        
        return tool
    }( )
    
    //MARK: - Oauth 授权
    //申请应用时分批的appkey
    private let client_id = "3291877803"
    
    //申请应用时分配的AppSecret
    private let client_secret = "3fb5c7fe1f19a1ac7327dd00057778aa"
    
    //授权回调地址
     let redirect_uri = "http://www.baidu.com/"
    
    //返回授权界面的URL地址
    func oauthURL( ) -> NSURL {
        //GET拼接登录界面请求地址
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(client_id)&redirect_uri=\(redirect_uri)"
//  print("\(urlString)")
    return NSURL(string: urlString)!
    }
    
    //MARK: - 网络工具类加载AccessToken, 只负责加载数据,让别人来处理数据(通过闭包)
    func loadAccessToken(code:String, finished:(result:[String:AnyObject]?,error:NSError?) -> ( )) {
        // url地址     3fb5c7fe1f19a1ac7327dd00057778aa
        let urlString = "https://api.weibo.com/oauth2/access_token"
        
        //请求参数
        let parameters = [
            "client_id":  client_id,
            "client_secret":  client_secret,
            "grant_type": "authorization_code",
            "code": code,
            "redirect_uri": redirect_uri
        ]
        
        //发送POST请求
        POST(urlString, parameters: parameters, success: { (_, result) -> Void in
//            print("result: \(result)")
            // as! 强制转换,f 有风险,如果转换不了,直接崩溃
            // as? 如果能转成功就转换,如果不能转换就返回nil
            finished(result: result as? [String : AnyObject] , error: nil)
            }) { (_, error) -> Void in
//                print("error: \(error)")
                finished(result: nil, error: error)
        }
    }
    
    //    init( ) {
//        super.init( )
//        
//        //做一些额外的事情
//    }
}
